// pages/classic/classic.js
import {
  ClassicModel
} from '../../models/classic.js'
import {
  LikeModel
} from '../../models/like.js'
const classicModel = new ClassicModel()
const likeModel = new LikeModel()

Component({
  /**
   * 页面的初始数据
   */
  properties: {
    cid: Number,
    type: Number
  },
  data: {
    // 最新一期数据
    classic: null,
    // 是否是最新一期
    latest: true,
    // 是否是第一期
    first: false,
    likeStatus: false,
    likeCount: 0
  },

  attached(options) {
    const cid = this.properties.cid
    const type = this.properties.type
    if (!cid) {
      classicModel.getLatest((res) => {
        this.setData({
          classic: res,
          likeCount: res.fav_nums,
          likeStatus: res.like_status
        })
      })
    } else {
      classicModel.getById(cid, type, res => {
        this._getLikeStatus(res.id, res.type)
        this.setData({
          classic: res,
          latest: classicModel.isLatest(res.index),
          first: classicModel.isFirst(res.index)
        })
      })
    }
  },

  methods: {

    // 点赞与取消点赞请求
    onLike: function(event) {
      // 获取点赞状态
      let like_or_cancel = event.detail.behavior
      // 发送请求
      likeModel.like(like_or_cancel, this.data.classic.id, this.data.classic.type)
    },

    // 获取下一期数据
    onNext: function(event) {
      this._updateClassic('next')
    },

    // 获取上一期数据
    onPrevious: function(event) {
      this._updateClassic('previous')
    },

    // 更新期刊数据
    _updateClassic(NextOrPrevious) {
      let index = this.data.classic.index
      classicModel.getClassic(index, NextOrPrevious, (res) => {
        this._getLikeStatus(res.id, res.type)
        this.setData({
          classic: res,
          latest: classicModel.isLatest(res.index),
          first: classicModel.isFirst(res.index)
        })
      })
    },

    // 获取点赞状态和次数
    _getLikeStatus(cid, type) {
      likeModel.getClassicLikeStatus(cid, type, (res) => {
        this.setData({
          likeStatus: res.like_status,
          likeCount: res.fav_nums
        })
      })
    }
  }

})